package com.gitee.ricesugar.mall.model.DAO;

import com.gitee.ricesugar.mall.model.POJO.DO.ProductDO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class ProductDAO {

    Connection connection;

    public ProductDAO() throws SQLException, ClassNotFoundException {
        connection = ConnectionPool.getInstance();
    }

    public ArrayList<ProductDO> listProducts() throws SQLException {

        PreparedStatement preparedStatement = connection.prepareStatement("select * from product");
        ResultSet resultSet = preparedStatement.executeQuery();

        ArrayList<ProductDO> products = new ArrayList<>();

        while (resultSet.next()){
            int id = resultSet.getInt("id");
            int product_id = resultSet.getInt("product_id");
            String name = resultSet.getString("name");
            double price = resultSet.getDouble("price");
            int stock = resultSet.getInt("stock");
            int sales = resultSet.getInt("sales");
            String img = resultSet.getString("img");
            products.add(new ProductDO(id, product_id, name, price, stock, sales, img));
        }

        return products;
    }

    public ProductDO getProduct(String pid) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement("select * from product where product_id = " + pid);
        ResultSet resultSet = preparedStatement.executeQuery();

        ArrayList<ProductDO> products = new ArrayList<>();

        while (resultSet.next()){
            int id = resultSet.getInt("id");
            int product_id = resultSet.getInt("product_id");
            String name = resultSet.getString("name");
            double price = resultSet.getDouble("price");
            int stock = resultSet.getInt("stock");
            int sales = resultSet.getInt("sales");
            String img = resultSet.getString("img");
            products.add(new ProductDO(id, product_id, name, price, stock, sales, img));
        }

        return products.get(0);
    }
}